package com.pig4cloud.pig.hu.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.hu.entity.Customer;
import com.pig4cloud.pig.hu.service.CustomerService;
import com.pig4cloud.pig.qc.entity.OrderEntity;
import com.pig4cloud.pig.qc.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@RestController
@RequestMapping("/carCustomer")
@RequiredArgsConstructor
public class CustomerController {

	private final CustomerService customerService;
	private final OrderService orderService;


	/*
	添加
	 */
	@PostMapping
	public R addCustomer(@RequestBody Customer customer){
		customerService.checkUnique(customer);
		return R.ok(customerService.save(customer));

	}

	/*
	分页查询
	 */
	@GetMapping("/page")
	public R<IPage<Customer>> getCustomerPage(@ParameterObject Page page, @ParameterObject Customer customer) {
		LambdaQueryWrapper<Customer> queryWrapper = Wrappers.<Customer>lambdaQuery()
				.like(StrUtil.isNotBlank(customer.getCustomerName()),
						Customer::getCustomerName,
						customer.getCustomerName())
				.like(StrUtil.isNotBlank(customer.getPhone()), Customer::getPhone, customer.getPhone())
				.orderByDesc(Customer::getCustomerId);
		IPage<Customer> customerPage = customerService.page(page, queryWrapper);
		customerPage.getRecords().forEach(c -> {
			long count = orderService.count(
					Wrappers.lambdaQuery(OrderEntity.class)
							.eq(OrderEntity::getCustomerId, c.getCustomerId())
			);
			c.setOrderCount((int) count);
		});
		return R.ok(customerPage);
	}
	/*
	修改
	 */
	@PutMapping
	public R update(@Valid @RequestBody Customer customer) {
		customerService.checkUnique(customer);
		customerService.updateById(customer);
		return R.ok();
	}
	/*
	通过id查询
	 */
	@GetMapping("/{id}")
	public R selectCustomer(@PathVariable long id){
		return R.ok(customerService.getById(id));
	}

}
